﻿using BCMongoData.StatisticsRequest;
using BCMongoEntity.StatisticsRequest;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Text;

namespace BCMongoService.StatisticsRequest
{
    public class StatisticsRequestMongoService: IStatisticsRequestMongoService
    {
        private readonly IStatisticsRequestMongoData _statisticsRequestMongoData;

        public StatisticsRequestMongoService(IStatisticsRequestMongoData statisticsRequestMongoData)
        {
            _statisticsRequestMongoData = statisticsRequestMongoData;
        }

        public void Append(StatisticsRequestEntity statisticsRequestEntity)
        {
            _statisticsRequestMongoData.Append(statisticsRequestEntity);
        }

        public StatisticsRequestEntity Get(int year, int month, int day, string accessApiName)
        {
            return _statisticsRequestMongoData.Get(year, month, day, accessApiName).Result;
        }

        public void Update(StatisticsRequestEntity statisticsRequestEntity)
        {
            var entity = this.Get(statisticsRequestEntity.Year, statisticsRequestEntity.Month, statisticsRequestEntity.Day, statisticsRequestEntity.AccessApiName);
            if (entity == null)
            {
                this.Append(statisticsRequestEntity);
                return;
            }

            bool successRequest = statisticsRequestEntity.SuccessTimes > 0;
            
            if (successRequest)
            {
                entity.SuccessTimes++;
            }
            else
            {
                entity.ErrorTimes++;
            }
            entity.AccessTimes++;
            entity.Parameters = statisticsRequestEntity.Parameters;
            entity.TemplateMessageId = statisticsRequestEntity.TemplateMessageId;
            entity.UpdateTime = DateTime.Now;
            var builder = Builders<StatisticsRequestEntity>.Update
                .Set(p => p.AccessTimes, entity.AccessTimes)
                .Set(p => p.SuccessTimes, entity.SuccessTimes)
                .Set(p => p.ErrorTimes, entity.ErrorTimes)
                .Set(p => p.Parameters, entity.Parameters)
                .Set(p => p.TemplateMessageId, entity.TemplateMessageId)
                .Set(p => p.UpdateTime, entity.UpdateTime);
            _statisticsRequestMongoData.Update(entity.Id, builder);
        }
    }
}
